package com.warm.mini.wework.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description ServletUtil
 * @Author warmchuang
 * @Date 2022/2/11 11:55
 */
public class ServletUtil {

    public ServletUtil() {
    }

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static HttpServletRequest getRequestSafely() {
        return RequestContextHolder.getRequestAttributes() == null ? null : ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static HttpServletResponse getResponse() {
        return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
    }

    public static String getHeader(String name) {
        return getRequest().getHeader(name);
    }

    public static Map<String, String> getRequestParams() {
        HttpServletRequest request = getRequest();
        Map<String, String> result = new HashMap();
        Enumeration names = request.getParameterNames();

        while(names.hasMoreElements()) {
            String name = (String)names.nextElement();
            result.put(name, request.getParameter(name));
        }

        return result;
    }

    public static String getUriBasePath() {
        HttpServletRequest request = getRequest();
        return getRequestScheme(request) + "://" + getHost(request);
    }

    public static String getHost(HttpServletRequest request) {
        String host = request.getHeader("X-Real-Host");
        if (StringUtils.isBlank(host) || "unknown".equalsIgnoreCase(host)) {
            host = request.getRemoteHost();
        }

        return host;
    }

    public static String getRequestScheme(HttpServletRequest request) {
        String scheme = request.getHeader("X-Scheme");
        if (StringUtils.isBlank(scheme) || "unknown".equalsIgnoreCase(scheme)) {
            scheme = request.getScheme();
        }

        return scheme;
    }

    public static String getRequestScheme() {
        return getRequestScheme(getRequest());
    }

    public static String getServerPort(HttpServletRequest request) {
        String port = request.getHeader("X-Server-Port");
        if (StringUtils.isBlank(port) || "unknown".equalsIgnoreCase(port)) {
            port = "" + request.getServerPort();
        }

        return port;
    }

    public static String getParam(String key) {
        return (String)getRequestParams().get(key);
    }
}
